<template>
  <section style="width: 100%;height: auto;" class="chart-box">
    <div v-show="!nodata" :id="id" ref="line" :style="styles" />
    <div v-show="nodata" class="no-data" :style="styles">
      <img src="@/assets/img/nodata/line_nodata.png" alt="">
      <div class="nodata-text flex align-center justify-center" style="color:#999">暂无数据</div>
    </div>
    <div
      v-if="showEventInfo"
      class="event-info"
      :style="eventStyle"
      @mouseleave="showEventInfo = false"
    >
      <div>事件类型：{{ activeEvent.eventType }}</div>
      <div>距离（m）：{{ activeEvent.position }}</div>
      <div>事件损耗（db）：{{ activeEvent.eventLoss }}</div>
      <div>反射衰减损耗（db）：{{ activeEvent.refractRate }}</div>
      <div>累计衰减损耗（db）：{{ activeEvent.linkLoss }}</div>
    </div>
  </section>
</template>
<script>
  import echarts from 'echarts'
  import RenderLine from './renderLine'
  export default {
    props: {
      id: {
        type: String,
        default: 'line'
      },
      styles: {
        type: Object,
        default() {
          return {}
        }
      },
      data: {
        type: Array,
        default() {
          return []
        }
      },
      eventList: {
        type: Array,
        default: () => []
      },
      xData: {
        type: Array,
        default() {
          return []
        }
      }
    },
    data() {
      return {
        nodata: false,
        showEventInfo: false,
        activeEvent: {},
        eventStyle: {}
      }
    },
    computed: {
      myChart() {
        if (document.getElementById(this.id)) {
          return echarts.init(document.getElementById(this.id))
        }
        return null
      }
    },
    watch: {
      data: {
        handler(newVal, oldVal) {
          if (newVal.length) {
            this.nodata = false
            this.$nextTick(() => {
              this.render()
            })
          } else {
            this.nodata = true
          }
        },
        deep: true
      }
    },
    mounted() {
      if (this.data.length) {
        this.$nextTick(() => {
          this.render()
        })
      } else {
        this.nodata = true
      }
    },
    beforeDestroy() {
      window.removeEventListener('resize', this.resize)
      try {
        if (this.myChart) {
          this.myChart.dispose()
        }
      } catch (error) {
        console.log(error)
      }
    },
    methods: {
      render() {
        if (this.myChart) {
          this.myChart.clear()
          this.myChart.setOption(new RenderLine({
            data: this.formateData()
          }))
          console.log(this.formateData())
          // 添加事件标识点击
          this.myChart.on('click', 'series.line', (e) => {
            this.eventItemCkick(e)
          })
          window.addEventListener('resize', this.resize)
        }
      },
      // 事件节点点击
      eventItemCkick(e) {
        // console.log(e)
        this.showEventInfo = true
        this.$nextTick(() => {
          const domHeight = document.querySelector('.event-info').offsetHeight
          const top = e.event.offsetY + domHeight / 2
          this.eventStyle = {
            top: (top > 0 ? top : 0) + 5 + 'px',
            left: e.event.offsetX - 5 + 'px'
          }
        })
        this.activeEvent = this.eventList[e.seriesIndex][e.dataIndex]
      },
      resize() {
        /* 把这个单独拎出来是因为如果写在window.addEventListener("resize", () => { this.myChart.resize()})里面
      当你需要移除这个监听事件的时候，这样写window.removeEventListener("resize")是不起作用的，而应该这样写
      window.addEventListener("resize", this.resieze)和window.removeEventListener('resize', this.resize)才可以正确移除*/
        this.myChart.resize()
      },
      // 利用markPoint将事件点放置到折线上
      formateData() {
        return this.data.map((series, index) =>
          this.getData(
            series,
            index,
            this.eventList[index]
          )
        )
      },
      getData(series, _index, eventList) {
        const markPointData = eventList.map((i, eventIndex) => {
          const yData = series.data.find(j => Number(j.value[0]) >= Number(i.position))
          return {
            coord: [(i.position).toString(), yData ? yData.value[1] : null],
            value: (eventIndex + 1).toString()
          }
        })
        const obj = {
          markPoint: {
            symbol: 'triangle',
            symbolOffset: [0, '50%'],
            symbolSize: 15,
            label: {
              fontSize: 8,
              offset: [0, 3]
            },
            data: markPointData
          }
        }
        return { ...series, ...obj }
      }
    }
  }
</script>
<style lang="scss" scoped>
.chart-box {
  .event-info {
    position: absolute;
    padding: 10px;
    width: auto;
    height: auto;
    z-index: 2;
    border-radius: 8px;
    background: rgba(0,0,0,0.5);
    color: '#fff';
    border: 1px solid #fff;
  }
}
</style>
